﻿namespace AutoSPInstallerGUI
{   
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using System.Windows;
    using System.Globalization;
    using System.Windows.Navigation;
    using System.Xml;
    using Classes;
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        Configuration _config = new Configuration();

        public MainWindow()
        {
            #if DEBUG
                AutoSPInstallerGUI.Classes.BindingErrorTraceListener.SetTrace();
            #endif

            InitializeComponent();
            CheckForUpdates();

            System.Windows.Controls.ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(DependencyObject), new FrameworkPropertyMetadata(Int32.MaxValue));

            Title = Title + " (" + Assembly.GetExecutingAssembly().GetName().Version + ")";

            tc_Main.IsEnabled = false;

            if (App.mArgs != null && App.mArgs.Count() > 0)
            {
                if (System.IO.Path.GetExtension(App.mArgs[0]) == ".xml")
                {
                    LoadXml(App.mArgs[0]);
                }
                else
                {
                    SplashScreenFix();
                    MessageBox.Show("This is not a supported file, it must be an XML file", "Error");
                }
            }
        }

        #region Menu
        private void LoadXml(string fileLocation)
        {
            try
            {
                // Supported XML Version
                const string supportedXML = "3.98";

                // Initializes the Config
                _config = Configuration.LoadFromFile(fileLocation);

                // Check if we have loaded the right file
                if (_config.Version == null)
                {
                    SplashScreenFix();
                    MessageBox.Show("It appears that you have not loaded the correct configuration XML", "Error");
                    return;
                }

                // Check XML Version Number
                if (_config.Version != supportedXML)
                {
                    SplashScreenFix();
                    MessageBox.Show("Please note that this version of AutoSPInstallerGUI has only been tested on AutoSPInstaller XML Version " + supportedXML + "\nYour version is: " + _config.Version + "\nPlease download the latest/older version of AutoSPInstaller from Source Code", "Error");
                    return;
                }

                // Sets the DataContext for the Main Window
                DataContext = _config;

                // Set up controls
                tc_Main.IsEnabled = true;
                Menu_SaveXML.IsEnabled = true;
                Menu_SaveASXML.IsEnabled = true;
                txt_StatusBar.Content = fileLocation;
                if (dd_WebApplications.Items.Count > 0)
                {
                    dd_WebApplications.SelectedIndex = 0;    
                }

                if (dd_Farm_ManagedAccounts.Items.Count > 0)
                {
                    dd_Farm_ManagedAccounts.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                SplashScreenFix();
                MessageBox.Show("There seems to be an issue with the XML file, please check that you are loading the correct file and that it has no issues:\n\n\n" + ex, "Error");
            }
        }

        private void SaveXml(string fileLocation)
        {
            try
            {
                // Save Config to File
                _config.SaveToFile(fileLocation);

                // Update the StatusBar with the new File Location
                txt_StatusBar.Content = fileLocation;

                // Notify the user that the file was saved
                MessageBox.Show("The XML file was saved to: " + fileLocation);
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error saving the XML file: \n" + ex.Message, "Error");
            }
        }

        private void Menu_LoadXML_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "AutoSPInstallerInput.xml";
            dlg.DefaultExt = ".xml";
            dlg.Filter = "Extensible Markup Language File (.xml)|*.xml";

            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                if (dlg.SafeFileName.Contains(" "))
                {
                    MessageBox.Show("AutoSPInstaller does not support XML files with spaces in the filename.\nYou may continue editing your file. Please rename it when youre done.", "Error");
                }

                LoadXml(dlg.FileName);
            }
        }

        private void Menu_SaveXML_Click(object sender, RoutedEventArgs e)
        {
            if (CheckData())
            {
                SaveXml(txt_StatusBar.Content.ToString());
            }
        }

        private void Menu_SaveASXML_Click(object sender, RoutedEventArgs e)
        {
            if (CheckData())
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName = string.Empty;
                dlg.DefaultExt = ".xml";
                dlg.Filter = "Extensible Markup Language File (.xml)|*.xml";

                Nullable<bool> result = dlg.ShowDialog();

                if (result == true)
                {
                    if (dlg.SafeFileName.Contains(" "))
                    {
                        MessageBox.Show("AutoSPInstaller does not support XML files with spaces in the filename.\nPlease resave your file with a new FileName!", "Error");
                        return;
                    }

                    SaveXml(dlg.FileName);
                }
            }
        }

        private void Menu_Exit_Click(object sender, RoutedEventArgs e)
        {
            Environment.Exit(0);
        }

        private void Menu_Help_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://autospinstallergui.codeplex.com");
        }

        private void Menu_Twitter_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://twitter.com/ivanjosipovic");
        }

        #endregion

        #region Misc

        /// <summary>
        /// Used for Data Validation
        /// </summary>
        /// <returns>true if succeeded</returns>
        private bool CheckData()
        {
            //// Checks for specific versions of SharePoint
            if (_config.Install.SPVersion == "2010")
            {
                // To do
            }
            else if (_config.Install.SPVersion == "2013")
            {
                //// Checks that Distributed Cache is not set to false
                if (_config.Farm.Services.DistributedCache.Start.ToLower() == "false")
                {
                    tc_Main.SelectedItem = tab_Farm;
                    tc_Farm.SelectedItem = tab_Farm_Services;
                    MessageBox.Show(string.Format("Please make sure that Distributed Cache is not set to false"), "Error");
                    return false;
                }
            }
            else
            {
                tc_Main.SelectedItem = tab_Install;
                MessageBox.Show(string.Format("Please reselect the SharePoint Version"), "Error");
                return false;
            }

            //// Check that FoundationWebApplication is not set to false
            if (_config.Farm.Services.FoundationWebApplication.Start.ToLower() == "false")
            {
                tc_Main.SelectedItem = tab_Farm;
                tc_Farm.SelectedItem = tab_Farm_Services;
                MessageBox.Show(string.Format("Please make sure that WebApplication is not set to false"), "Error");
                return false;
            }

            //// Check if any Web Applications Exist
            if (!_config.WebApplications.WebApplication.Any())
            {
                MessageBox.Show("AutoSPInsatller will fail if there are no Web Applications. Create at least one Web Application", "Error");
                return false;
            }
                
            foreach (ConfigurationWebApplicationsWebApplication webApplication in _config.WebApplications.WebApplication)
            {
                //// Check to see if any Site Collection URL Contains :80 or :443
                if (webApplication.SiteCollections.Any(x => x.siteUrl.EndsWith(":80") || x.siteUrl.EndsWith(":443") || x.siteUrl.EndsWith(":80/") || x.siteUrl.EndsWith(":443/") || x.siteUrl.Contains(":80/") || x.siteUrl.Contains(":443/")))
                {
                    tc_Main.SelectedItem = tab_WebApplications;
                    dd_WebApplications.SelectedItem = webApplication;
                    dd_WebApplications_SelectionChanged(null, null);
                    MessageBox.Show("The SiteCollection Site URL should not contain :443 or :80", "Error");
                    return false;
                }

                //// Check to see an associated Managed Account exists
                if (!_config.Farm.ManagedAccounts.Any(x => x.CommonName.ToLower() == webApplication.type.ToLower()))
                {
                    tc_Main.SelectedItem = tab_WebApplications;
                    dd_WebApplications.SelectedItem = webApplication;
                    dd_WebApplications_SelectionChanged(null, null);
                    MessageBox.Show("The Managed Account with the Common Name: " + webApplication.type + " does not exist!", "Error");
                    return false;
                }

                //// Trim the Web Application Url for /
                webApplication.url = webApplication.url.TrimEnd("/".ToCharArray());

                //// Trim the Site Collection URls for /
                if (webApplication.SiteCollections.Any())
                {
                    foreach (ConfigurationWebApplicationsWebApplicationSiteCollection siteCollection in webApplication.SiteCollections)
                    {
                        siteCollection.siteUrl = siteCollection.siteUrl.TrimEnd("/".ToCharArray());
                    }
                }

                //// Warns the user if a WebApplication is not using Claims in 2013 mode.
                if (_config.Install.SPVersion == "2013")
                {
                    if (webApplication.useClaims == false)
                    {
                        tc_Main.SelectedItem = tab_WebApplications;
                        dd_WebApplications.SelectedItem = webApplication;
                        dd_WebApplications_SelectionChanged(null, null);
                        MessageBox.Show(string.Format(webApplication.name + " is using Classic Authentication.\nPlease Note that Claims Authentication is recommended in SharePoint 2013. Classic Authentication is deprecated. If you know what you're doing you may proceed."), "Warning");
                    }
                }
            }

            //// If the Search Service is to be provisioned
            if (_config.ServiceApps.EnterpriseSearchService.Provision.ToLower() != "false")
            {
                //// Check that SearchService Managed Account exists
                if (_config.Farm.ManagedAccounts.All(x => x.CommonName.ToLower() != "searchservice"))
                {
                    tc_Main.SelectedItem = tab_Farm;
                    tc_Farm.SelectedItem = tab_Farm_Main;
                    MessageBox.Show(string.Format("The Managed Account with the Common Name: SearchService does not exist. This is required by the Search Service."), "Error");
                    return false;
                }

                //// Checks for specific versions of SharePoint
                if (_config.Install.SPVersion == "2010")
                {
                    //// Checks that all of the Search Service Components have at least one Server
                    //if (!_config.ServiceApps.EnterpriseSearchService.EnterpriseSearchServiceApplications[0].CrawlComponent.Any() || 
                    //    !_config.ServiceApps.EnterpriseSearchService.EnterpriseSearchServiceApplications[0].QueryComponent.Any() || 
                    //    !_config.ServiceApps.EnterpriseSearchService.EnterpriseSearchServiceApplications[0].SearchQueryAndSiteSettingsServers.Any() || 
                    //    !_config.ServiceApps.EnterpriseSearchService.EnterpriseSearchServiceApplications[0].AdminComponent.Server.Any())
                    //{
                    //    tc_Main.SelectedItem = tab_ServiceApplications;
                    //    tc_Farm_ServiceApplications.SelectedItem = tab_Search;
                    //    tc_ServiceApps_EnterpriseSearch.SelectedItem = tab_ServiceApps_EnterpriseSearchService_EnterpriseSearchServiceApplications;
                    //    MessageBox.Show(string.Format("Please make sure that all of the Search Topology components contain at least one Server"), "Error");
                    //    return false;
                    //}
                }
                else
                {
                    //// 2013
                    //// Checks that all of the Search Service Components have at least one Server
                    //if (!_config.ServiceApps.EnterpriseSearchService.EnterpriseSearchServiceApplications[0].CrawlComponent.Any() ||
                    //    !_config.ServiceApps.EnterpriseSearchService.EnterpriseSearchServiceApplications[0].QueryComponent.Any() ||
                    //    !_config.ServiceApps.EnterpriseSearchService.EnterpriseSearchServiceApplications[0].SearchQueryAndSiteSettingsServers.Any() ||
                    //    !_config.ServiceApps.EnterpriseSearchService.EnterpriseSearchServiceApplications[0].AdminComponent.Server.Any() ||
                    //    !_config.ServiceApps.EnterpriseSearchService.EnterpriseSearchServiceApplications[0].IndexComponent.Any() ||
                    //    !_config.ServiceApps.EnterpriseSearchService.EnterpriseSearchServiceApplications[0].ContentProcessingComponent.Any() ||
                    //    !_config.ServiceApps.EnterpriseSearchService.EnterpriseSearchServiceApplications[0].AnalyticsProcessingComponent.Any())
                    //{
                    //    tc_Main.SelectedItem = tab_ServiceApplications;
                    //    tc_Farm_ServiceApplications.SelectedItem = tab_Search;
                    //    tc_ServiceApps_EnterpriseSearch.SelectedItem = tab_ServiceApps_EnterpriseSearchService_EnterpriseSearchServiceApplications;
                    //    MessageBox.Show(string.Format("Please make sure that all of the Search Topology components contain at least one Server"), "Error");
                    //    return false;
                    //}
                }
            }

            //// Check that Mysite Host is set up correctly
            if (_config.ServiceApps.UserProfileServiceApp.Provision.ToLower() != "false")
            {
                if (_config.WebApplications.WebApplication.All(x => x.type.ToLower() != "mysitehost") && string.IsNullOrEmpty(_config.ServiceApps.UserProfileServiceApp.MySiteHostLocation))
                {
                    MessageBox.Show(string.Format("Mysites require either a WebApplication with a Type MySiteHost or a URL of a WebApplication in the MySite Host Location field."),"Error");
                    return false;
                }
            }

            // Used to check the PassPhrase complexity
            // Code borrowed from AutoSPInstaller
            if (_config.Farm.Passphrase != string.Empty)
            {
                string password = _config.Farm.Passphrase;
                int count = 0;
                if (Regex.IsMatch(password, "[a-z]")) { count++; }
                if (Regex.IsMatch(password, "[A-Z]")) { count++; }
                if (Regex.IsMatch(password, "[0-9]")) { count++; }
                if (Regex.IsMatch(password, "[^a-zA-Z0-9]")) { count++; }

                if (count < 3 || password.Length < 8)
                {
                    tc_Main.SelectedItem = tab_Farm;
                    txt_Farm_Passphrase.Focus();
                    MessageBox.Show("Farm passphrase does not meet complexity requirements.\nIt must be at least 8 characters long and contain three of these types:\nUpper case letters\nLower case letters\nDigits\nOther characters", "Error");
                    return false;
                }
            }

            // Check if Install.ConfigFile is empty
            if (String.IsNullOrEmpty(_config.Install.ConfigFile))
            {
                tc_Main.SelectedItem = tab_Install;
                MessageBox.Show("The Script will fail if the Config File textbox is empty. Set it to config.xml if you're unsure.", "Error");
                return false;
            }

            return true;
        }

        /// <summary>
        /// Checks for new version of the applications by looking at the Codeplex RSS Feed
        /// </summary>
        private void CheckForUpdates()
        {
            try
            {
                string rssurl = "http://autospinstallergui.codeplex.com/project/feeds/rss?projectrssfeed=codeplex://release/autospinstallergui";
                XmlDocument rssXml = new XmlDocument();
                rssXml.Load(rssurl);

                XmlNodeList rssNodeList = rssXml.SelectNodes("rss/channel/item");

                // Gets the newest rss entries title, link and description
                if (rssNodeList != null)
                {
                    XmlNode rssSubNode = rssNodeList[0].SelectSingleNode("title");
                    string title = rssSubNode != null ? rssSubNode.InnerText : string.Empty;
                    rssSubNode = rssNodeList[0].SelectSingleNode("link");
                    string link = rssSubNode != null ? rssSubNode.InnerText : string.Empty;
                    rssSubNode = rssNodeList[0].SelectSingleNode("description");
                    string desc = rssSubNode != null ? rssSubNode.InnerText : string.Empty;

                    // Strips the HTML code from the RSS Description
                    string strippeddesc = Regex.Replace(desc.Replace("<br />", "\n").Replace("&quot;", "\"").Replace("&#39;","'"), "<.*?>", string.Empty);

                    // Gets the server and client version strings
                    string server = title.Substring(title.IndexOf(":", StringComparison.Ordinal) + 2, title.IndexOf("(", StringComparison.Ordinal) - title.IndexOf(":", StringComparison.Ordinal) - 3);
                    string client = Assembly.GetExecutingAssembly().GetName().Version.ToString();

                    // Converts the version string to a List of integers
                    List<int> lstServer = server.Split('.').ToList().ConvertAll(Convert.ToInt32);
                    List<int> lstClient = client.Split('.').ToList().ConvertAll(Convert.ToInt32);

                    // Check if the RSS version contains a version higher than the client
                    for (int i = 0; i <= 3; i++)
                    {
                        if (lstServer[i] < lstClient[i])
                        {
                            return;
                        }
                        if (lstServer[i] > lstClient[i])
                        {
                            SplashScreenFix();
                            if (MessageBox.Show(title + "\n" + strippeddesc + "\n\nClick OK to go to the Download Page.", "Update Found!", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                            {
                                System.Diagnostics.Process.Start(link);
                                return;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Message == "The remote name could not be resolved: 'autospinstallergui.codeplex.com'")
                {
                    SplashScreenFix();
                    MessageBox.Show("Unable to check for a new version, you most likely don't have internet access.", "Warning");
                }
            }
        }

        /// <summary>
        /// Trims the Textbox text if needed
        /// </summary>
        /// <param name="sender">Textbox</param>
        /// <param name="e"></param>
        private void TrimTextBox(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.TextBox senderTextBox = (System.Windows.Controls.TextBox)sender;

            if (senderTextBox.Text.EndsWith(" ") || senderTextBox.Text.StartsWith(" "))
            {
                senderTextBox.Text = senderTextBox.Text.Trim();
            }
        }

        /// <summary>
        /// Assists in opening link for TextBlocks
        /// Code from: http://stackoverflow.com/questions/2092890/add-hyperlink-to-textblock-wpf/2093016#2093016
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            System.Diagnostics.Process.Start(e.Uri.ToString());
        }

        /// <summary>
        /// Fix for SplashScreen closing MsgBoxes
        /// http://connect.microsoft.com/VisualStudio/feedback/details/600197/wpf-splash-screen-dismisses-dialog-box
        /// </summary>
        private void SplashScreenFix()
        {
            Window temp = new Window { Visibility = Visibility.Hidden };
            temp.Show();
        }
        #endregion

        #region Farm Tab
        private void rdo_Install_SPVersion_2010_Checked(object sender, RoutedEventArgs e)
        {
            dd_WebApplications_SiteCollections_Template.ItemsSource = _config.WebTemplates.Where(x => x.CompatibilityLevel == 14);
        }

        private void rdo_Install_SPVersion_2013_Checked(object sender, RoutedEventArgs e)
        {
            dd_WebApplications_SiteCollections_Template.ItemsSource = _config.WebTemplates.GroupBy(x => x.Name).Select(grp => grp.First());
        }
        
        private void dd_Farm_ManagedAccounts_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (dd_Farm_ManagedAccounts.SelectedIndex != -1)
            {
                if (_config.Farm.ManagedAccounts[dd_Farm_ManagedAccounts.SelectedIndex].CommonName.ToLower() == "spservice")
                {
                    lbl_Farm_ManagedAccounts_Note.Text = "Please Note: This is the Service Account which will be used as the Application Pool Account for most of the Service Applications. By default, only Search uses a separate Managed Account.";
                    return;
                }
                if (_config.Farm.ManagedAccounts[dd_Farm_ManagedAccounts.SelectedIndex].CommonName.ToLower() == "searchservice")
                {
                    lbl_Farm_ManagedAccounts_Note.Text = "Please Note: This is the Service Account which will be used by the Search Service.";
                    return;
                }

                lbl_Farm_ManagedAccounts_Note.Text = "Please Note: This Managed Account is used by " + _config.WebApplications.WebApplication.Count(x => String.Equals(x.type, _config.Farm.ManagedAccounts[dd_Farm_ManagedAccounts.SelectedIndex].CommonName, StringComparison.CurrentCultureIgnoreCase)) + " WebApplications";
            }
            else
            {
                lbl_Farm_ManagedAccounts_Note.Text = "";
            }
        }
        
        private void btn_Farm_ManagedAccounts_Add_Click(object sender, RoutedEventArgs e)
        {
            ConfigurationFarmManagedAccount managedAccount = new ConfigurationFarmManagedAccount();
            managedAccount.Username = "Domain\\TempAccount" + _config.Farm.ManagedAccounts.Count();
            managedAccount.Password = "Change Me";
            managedAccount.CommonName = "Other";
            _config.Farm.ManagedAccounts.Add(managedAccount);
            dd_Farm_ManagedAccounts.SelectedIndex = dd_Farm_ManagedAccounts.Items.Count - 1;          
        }

        private void btn_Farm_ManagedAccounts_Remove_Click(object sender, RoutedEventArgs e)
        {
            if (dd_Farm_ManagedAccounts.SelectedIndex != -1)
            {
                // Prevents users deleting the spservics Managed Account
                if (_config.Farm.ManagedAccounts[dd_Farm_ManagedAccounts.SelectedIndex].CommonName.ToLower() == "spservice")
                {
                    MessageBox.Show("This Account is required and should not be deleted.\nHowever, you can change the Account Info", "Warning");
                    return;
                }

                // Prevents users deleting the SearchService Account if Search is to be provisioned.
                if (_config.Farm.ManagedAccounts[dd_Farm_ManagedAccounts.SelectedIndex].CommonName.ToLower() == "searchservice" && _config.ServiceApps.EnterpriseSearchService.Provision.ToLower() != "false")
                {
                    MessageBox.Show("This Account is required by the Search Service. Set Provision to false on the Search Service in order to be able to delete this account.", "Warning");
                    return;
                }

                // Checks that the Managed Account is not used by any Web Applications.
                if (_config.WebApplications.WebApplication.Where(x => x.type.ToLower() == _config.Farm.ManagedAccounts[dd_Farm_ManagedAccounts.SelectedIndex].CommonName.ToLower()).Any())
                {
                    MessageBox.Show("This Account is required by a WebApplication, please delete it prior to deleting this Managed Account.", "Warning");
                    return;
                }

                _config.Farm.ManagedAccounts.RemoveAt(dd_Farm_ManagedAccounts.SelectedIndex);
                dd_Farm_ManagedAccounts.SelectedIndex = dd_Farm_ManagedAccounts.Items.Count - 1;

            }
        }
        #endregion

        #region Web Applications
        private void dd_WebApplications_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (dd_WebApplications_ManagedPaths.Items.Count > 0)
            {
                dd_WebApplications_ManagedPaths.SelectedIndex = 0;
            }

            if (dd_WebApplications_SiteCollections.Items.Count > 0)
            {
                dd_WebApplications_SiteCollections.SelectedIndex = 0;
            }
        }

        private void btn_WebApplications_Add_Click(object sender, RoutedEventArgs e)
        {
            ConfigurationWebApplicationsWebApplication webApplication = new ConfigurationWebApplicationsWebApplication();
            webApplication.type = "Other";
            webApplication.name = "New" + _config.WebApplications.WebApplication.Count();
            webApplication.applicationPool = "WebApplication Pool";
            webApplication.url = "http://localhost";
            webApplication.port = (80 + _config.WebApplications.WebApplication.Count()).ToString(CultureInfo.InvariantCulture);
            webApplication.Database.Name =  webApplication.name + "_ContentDB_" + _config.WebApplications.WebApplication.Count();
            webApplication.UseHostHeader = true;
            webApplication.AddURLToLocalIntranetZone = true;
            webApplication.useClaims = true;
            webApplication.useBasicAuthentication = false;
            webApplication.useOnlineWebPartCatalog = false;
            webApplication.Database = new ConfigurationWebApplicationsWebApplicationDatabase();
            webApplication.Database.DBServer = string.Empty;
            webApplication.Database.DBAlias = new ConfigurationWebApplicationsWebApplicationDatabaseDBAlias();
            webApplication.Database.DBAlias.Create = false;
            webApplication.Database.DBAlias.DBInstance = "SERVER\\INSTANCE";
            webApplication.Database.DBAlias.DBPort = string.Empty;

            webApplication.ManagedPaths = new System.Collections.ObjectModel.ObservableCollection<ConfigurationWebApplicationsWebApplicationManagedPath>();
            webApplication.SiteCollections = new System.Collections.ObjectModel.ObservableCollection<ConfigurationWebApplicationsWebApplicationSiteCollection>();

            if (_config.WebApplications.WebApplication == null)
            {
                _config.WebApplications.WebApplication = new System.Collections.ObjectModel.ObservableCollection<ConfigurationWebApplicationsWebApplication>();
            }

            _config.WebApplications.WebApplication.Add(webApplication);
            dd_WebApplications.SelectedIndex = dd_WebApplications.Items.Count - 1;
        }

        private void btn_WebApplications_Remove_Click(object sender, RoutedEventArgs e)
        {
            if (dd_WebApplications.SelectedIndex != -1)
            {
                _config.WebApplications.WebApplication.RemoveAt(dd_WebApplications.SelectedIndex);
                dd_WebApplications.SelectedIndex = dd_WebApplications.Items.Count - 1;
            }
        }

        private void btn_WebApplications_ManagedPaths_Add_Click(object sender, RoutedEventArgs e)
        {
                ConfigurationWebApplicationsWebApplicationManagedPath managedPath = new ConfigurationWebApplicationsWebApplicationManagedPath();
                managedPath.relativeUrl = "ChangeMe" + dd_WebApplications_ManagedPaths.Items.Count;
                managedPath.@explicit = false;

                _config.WebApplications.WebApplication[dd_WebApplications.SelectedIndex].ManagedPaths.Add(managedPath);
                dd_WebApplications_ManagedPaths.SelectedIndex = dd_WebApplications_ManagedPaths.Items.Count - 1;
        }

        private void btn_WebApplications_ManagedPaths_Remove_Click(object sender, RoutedEventArgs e)
        {
            if (dd_WebApplications_ManagedPaths.SelectedIndex != -1)
            {
                _config.WebApplications.WebApplication[dd_WebApplications.SelectedIndex].ManagedPaths.RemoveAt(dd_WebApplications_ManagedPaths.SelectedIndex);
                dd_WebApplications_ManagedPaths.SelectedIndex = dd_WebApplications_ManagedPaths.Items.Count - 1;
            }
        }
        
        private void btn_WebApplications_SiteCollections_Add_Click(object sender, RoutedEventArgs e)
        {
            ConfigurationWebApplicationsWebApplicationSiteCollection siteCollection = new ConfigurationWebApplicationsWebApplicationSiteCollection();
            siteCollection.siteUrl = _config.WebApplications.WebApplication[dd_WebApplications.SelectedIndex].url.TrimEnd('/') + "/sites/Site" + _config.WebApplications.WebApplication[dd_WebApplications.SelectedIndex].SiteCollections.Count;
            siteCollection.Owner = "Domain\\ChangeMe";
            siteCollection.HostNamedSiteCollection = false;
            siteCollection.Name = "New Site";
            siteCollection.Description = "New Site";
            siteCollection.SearchUrl = "http://localhost/search";
            siteCollection.CustomTemplate = false;
            siteCollection.Template = "STS#0";
            siteCollection.LCID = "1033";
            siteCollection.Locale = "en-us";
            siteCollection.Time24 = false;

            _config.WebApplications.WebApplication[dd_WebApplications.SelectedIndex].SiteCollections.Add(siteCollection);
            dd_WebApplications_SiteCollections.SelectedIndex = dd_WebApplications_SiteCollections.Items.Count - 1;
        }

        private void btn_WebApplications_SiteCollections_Remove_Click(object sender, RoutedEventArgs e)
        {
            if (dd_WebApplications_SiteCollections.SelectedIndex != -1)
            {
                _config.WebApplications.WebApplication[dd_WebApplications.SelectedIndex].SiteCollections.RemoveAt(dd_WebApplications_SiteCollections.SelectedIndex);
                dd_WebApplications_SiteCollections.SelectedIndex = dd_WebApplications_SiteCollections.Items.Count - 1;
            }
        }

        #endregion
    }
}